/*
 * Copyright (c) 2005 Chris Richardson
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 


package net.chrisrichardson.ormunit.hibernate;

import java.io.Serializable;

import net.chrisrichardson.util.TxnCallback;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.hibernate.SessionFactory;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.HibernateTransactionManager;

/**
 * Base class for writing unit tests that create, find, update and delete
 * persistent objects using Hibernate
 * 
 * @author cer
 * 
 */

public abstract  class HibernatePersistenceTests<Q> extends HibernateORMTestCase {
	
	protected HibernateTemplate hibernateTemplate;
	protected Q txnThis;

	private HibernatePersistenceTestsStrategy transactionStrategy;

	public HibernatePersistenceTests() {
		setDependencyCheck(false);
	}

	private final class LocalTransactionInterceptor implements MethodInterceptor {
		private final class MyTxnCallback implements TxnCallback {
			private final MethodInvocation mi;
			private Object returnValue;

			private MyTxnCallback(MethodInvocation mi) {
				this.mi = mi;
			}

			public void execute() throws Throwable {
				returnValue = mi.proceed();
			}

			public Object getReturnValue() {
				return returnValue;
			}
		}

		public Object invoke(final MethodInvocation mi) throws Throwable {
			MyTxnCallback callback = new MyTxnCallback(mi);
			doWithTransaction(callback);
			return callback.getReturnValue();
		}
	}


	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.hibernateTemplate = new HibernateTemplate(sessionFactory);
	}
	
	public void setTransactionStrategy(HibernatePersistenceTestsStrategy strategy) {
		this.transactionStrategy = strategy;
	}

	protected void onSetUp() throws Exception {
		super.onSetUp();
		if (transactionStrategy == null) {
			transactionStrategy = makeDefaultTransactionStrategy();
		}
		hibernateTemplate.setFlushMode(transactionStrategy.getFlushMode());
		transactionStrategy.onSetUp();
		txnThis = makeTxnThis();
	}

	protected RollbackTransactionHibernatePersistenceTestsStrategy makeDefaultTransactionStrategy() {
		return new RollbackTransactionHibernatePersistenceTestsStrategy(hibernateTemplate, makeDefaultTransactionManager());
	}

	protected HibernateTransactionManager makeDefaultTransactionManager() {
		return new HibernateTransactionManager(hibernateTemplate.getSessionFactory());
	}

    protected Q makeTxnThis() {
		ProxyFactory pf = new ProxyFactory(this);
		pf.setProxyTargetClass(true);
		pf.addAdvice(new LocalTransactionInterceptor());
		Object proxy = pf.getProxy();
		return (Q) proxy;
	}

	@Override
	protected void onTearDown() throws Exception {
		super.onTearDown();
		transactionStrategy.onTearDown();
	}

	protected Serializable save(Object r) {
		return hibernateTemplate.save(r);
	}

	protected <T> T load(Class<T> type, Serializable id) {
		return (T) hibernateTemplate.load(type, id);
	}

	protected <T> T get(Class<T> type, Serializable id) {
		return (T)hibernateTemplate.get(type, id);
	}

	protected void doWithTransaction(TxnCallback cb) {
		transactionStrategy.doWithTransaction(cb);
	}

	protected HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	protected void delete(Class type) {
		HibernateTemplate t = getHibernateTemplate();
		t.deleteAll(t.find("from " + type.getName()));
	}

	protected void delete(Object object) {
		getHibernateTemplate().delete(object);
	}

}